import axios from '../js_sdk/xtshadow-axios/axios.min'
import store from '../store'
import {
	paramsToStr,
	toast
} from './tools'


import {
	baseURL,
	suiteIds
} from '../config/app'


function checkParams(params) {
	if (typeof params != 'object') return params
	for (let key in params) {
		const value = params[key];
		if (value === null || value === undefined || value === "") {
			delete params[key];
		}
	}
	return params;
}

function WXlogin() {
	wx.qy.login({
		suiteId: suiteIds, //非必填，第三方应用的suiteid，自建应用不填。若第三方小程序绑定多个第三方应用时，建议填上该字段
		success: function(res) {
			//console.log(res);
			if (res.code) {
				//发起网络请求
				wx.request({
					url: `${baseURL}/QwThird/code2Session/oauthCallback`,
					data: {
						code: res.code
					},
					success(res) {
						try {
							uni.setStorageSync('qw', {
								...res.data.data
							});
						} catch (e) {
							console.log(e);
						}
						//console.log(res.data.data,'loginSuccMsg')
					},
					fail(e) {
						console.log(e, '请求后端url失败')
					}
				})
			} else {
				console.log('登录失败！' + res.errMsg)
			}
		}
	});
}

function checkSissionKey() {
	wx.qy.checkSession({
		success: function(e) {
			console.log(e, 'session没有过期');
		},
		fail: function() {
			// session_key 已经失效，需要重新执行登录流程
			WXlogin() //重新登录
		}
	})
}


const service = axios.create({
	baseURL: baseURL,
	timeout: 10000,
	header: {
		'content-type': 'application/json;charset:utf-8'
	},

});


// request拦截器
service.interceptors.request.use(
	config => {
		config.data = checkParams(config.data)
		config.params = checkParams(config.params)
		if (config.method == 'GET') {
			config.url += paramsToStr(config.params)
		}
		const Store = uni.getStorageSync('token');
		//console.log(Store);
		config.header.Authorization = 'Bearer ' + Store.token
		config.header.Cookie = 'sidebarStatus=0; Admin-Token=' + Store.token

		uni.showLoading({
			title: "加载数据中"
		})
		checkSissionKey()
		return config
	},
	error => {
		uni.hideLoading()
		// Do something with request error
		console.log(error) // for debug
		Promise.reject(error)
	}
)

// response 拦截器
service.interceptors.response.use(
	async (response) => {
			uni.hideLoading()
			//console.log(response,123);
			if (response.data.code !== 200) {
				uni.showToast({
					title: response.data.msg,
					icon: "none"
				})
				//this.$u.toast()
			}

			return Promise.resolve(response.data)
		},
		error => {
			// uni.showToast({
			// 	title: "系统错误",
			// 	icon: "none"
			// })
			//if(response.data.code !== 200){
			if (error.response.data.message) {
				uni.showToast({
					title: error.response.data.message,
					icon: "none"
				})
			}
			//this.$u.toast()
			//}
			uni.hideLoading()
			//console.log(error)
			console.log('err' + error) // for debug
			return Promise.reject(error)
		}
)

export default service